<template>
    <n-drawer :show="active" :width="width" @update:show="(flag:boolean) => (active = flag)">
        <n-drawer-content :native-scrollbar="false" title="订单列表" closable>
            <n-space vertical :size="12">
                <n-space justify="space-between">
                    <n-space></n-space>
                    <n-space>
                        <n-form inline :model="param" :show-label="false" :show-feedback="false" ref="formRef">
                            <n-form-item>
                                <n-select
                                    v-model:value="param.query.state"
                                    style="width: 120px"
                                    placeholder="订单状态"
                                    :options="[
                                        { label: '所有状态', value: 0 },
                                        { label: '等待支付', value: 1 },
                                        { label: '等待服务', value: 2 },
                                        { label: '租赁中', value: 3 },
                                        { label: '已完成交车', value: 4 },
                                        { label: '订单取消', value: 9 },
                                    ]"
                                />
                            </n-form-item>
                            <n-form-item>
                                <n-input v-model:value="param.query.orderid" style="width: 150px" clearable placeholder="订单编号" />
                            </n-form-item>
                            <n-form-item>
                                <n-input v-model:value="param.query.name" style="width: 100px" clearable placeholder="客户名称" />
                            </n-form-item>
                            <n-form-item>
                                <n-input v-model:value="param.query.mob" style="width: 100px" clearable placeholder="客户手机" />
                            </n-form-item>
                            <n-form-item>
                                <n-tooltip trigger="hover">
                                    <template #trigger>
                                        <n-date-picker v-model:value="dates" style="width: 250px" type="daterange" :update-value-on-close="true" />
                                    </template>
                                    下单时间
                                </n-tooltip>
                            </n-form-item>
                        </n-form>

                        <n-button @click="doQuery">
                            <template #icon>
                                <n-icon :component="YoutubeSearchedForRound" />
                            </template>
                        </n-button>
                    </n-space>
                </n-space>
                <n-data-table :row-props="rowProps" striped size="large" type="selection" :row-key="(row:any) => row.id" :columns="columns" :data="items" />
                <n-space justify="end">
                    <n-pagination
                        show-size-picker
                        :page="param.pager.page"
                        :page-size="param.pager.size"
                        :page-count="pager.all"
                        :page-sizes="[10, 25, 50, 100]"
                        @update:page="onChangePage"
                        @update:page-size="onChangeSize"
                    >
                        <template #prefix="{}">当前 {{ pager.now }} / {{ pager.all }} 页，共 {{ pager.row }} 条数据</template>
                    </n-pagination>
                </n-space>
            </n-space>
            <Order :item="data" v-model:show="viewActive" v-if="viewActive"></Order>

            <template #footer>
                <n-space justify="end">
                    <n-button type="tertiary" :disabled="loading" @click="() => (active = false)">
                        <template #icon>
                            <n-icon :component="CloseRound" />
                        </template>
                        关闭
                    </n-button>
                </n-space>
            </template>
        </n-drawer-content>
    </n-drawer>
</template>

<script lang="ts" setup>
import { h, ref, computed, onBeforeMount, watch } from 'vue'
import { CloseRound, YoutubeSearchedForRound } from '@vicons/material'
import { NSpace, NText, NIcon, NButton, NTag } from 'naive-ui'

import { Http, Filters } from '@/libs'
import { useStore } from '@/store'

import Order from '../order/View.vue'

import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn' // 导入本地化语言
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.locale('zh-cn')
dayjs.extend(customParseFormat)

const store = useStore()
const width = computed(() => Math.max(store.state.browser.innerWidth * 0.4, 1000))

const loading = ref(false)

const prop = defineProps({
    show: {
        type: Boolean,
        required: true,
    },
    item: {
        type: Object,
        default: {},
    },
})

const emit = defineEmits(['update:show', 'refresh'])

const active = computed({
    get: () => prop.show,
    set: val => emit('update:show', val),
})

const rowProps = (row: any) => {
    return {
        style: 'cursor: pointer;',
        onClick: () => {
            data.value = row
            viewActive.value = true
        },
    }
}

const columns = [
    {
        title: '订单编号',
        key: 'id',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []

            comps[comps.length] = h(NText, { code: true }, { default: () => 'D' + row.id })
            if (row.state == 1) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false, type: 'error' }, { default: () => '等待支付' })
            } else if (row.state == 2) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false, type: 'warning' }, { default: () => '等待服务' })
            } else if (row.state == 3) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false, type: 'success' }, { default: () => '租赁中' })
            } else if (row.state == 4) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false, type: 'info' }, { default: () => '已完成交车' })
            } else if (row.state == 9) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false }, { default: () => '订单取消' })
            }
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },

    {
        title: '承租人',
        key: 'customer',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => row.customer.name })
            comps[comps.length] = h(NText, { code: true }, { default: () => row.customer.phone })
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '租期时间',
        key: 'begin',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => '起：' + row.begin })
            comps[comps.length] = h('span', {}, { default: () => '至：' + row.close })
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },

    {
        title: '租金信息',
        key: 'rent',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => `租金：${Filters.money(row.rent.total)} / 押金：${Filters.money(row.deposit.total)}` })
            comps[comps.length] = h('span', {}, { default: () => `日租：${Filters.money(row.rent.day)} / 服务：${Filters.money(row.rent.srvs)}` })
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '出租人/店',
        key: 'agency',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            if (row.agency.clerk) {
                comps[comps.length] = h('span', {}, { default: () => `${row.agency.clerk.name} / ${row.agency.merchant.name}` })
                comps[comps.length] = h('span', {}, { default: () => `佣金：${Filters.money(row.agency.total)}` })
            } else {
                comps[comps.length] = h('span', {}, { default: () => `门店订单` })
                comps[comps.length] = h('span', {}, { default: () => `无中介方` })
            }

            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '订单时间',
        key: 'times',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => `下单：${row.times.create}` })
            if (row.state == 9) {
                comps[comps.length] = h('span', {}, { default: () => `取消：${row.times.cancel}` })
            } else if (row.state == 4) {
                comps[comps.length] = h('span', {}, { default: () => `完成：${row.times.finish}` })
            } else if (row.state == 3) {
                comps[comps.length] = h('span', {}, { default: () => `交车：${row.times.delivery}` })
            } else if (row.state == 2) {
                comps[comps.length] = h('span', {}, { default: () => `支付：${row.times.paid}` })
            }

            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
]

const onChangeSize = (size: number) => {
    param.value.pager.page = 1
    param.value.pager.size = size
    execLoad()
}

const onChangePage = (page: number) => {
    param.value.pager.page = page
    execLoad()
}

const dates = ref<number[]>([dayjs().subtract(1, 'month').valueOf(), dayjs().valueOf()])
watch([dates, () => dates.value], (nv, _ov) => {
    let v = nv[0] as number[]
    param.value.query.begin = dayjs(v[0]).format('YYYY-MM-DD')
    param.value.query.close = dayjs(v[1]).format('YYYY-MM-DD')
})

const param = ref({
    query: {
        begin: dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
        close: dayjs().format('YYYY-MM-DD'),
        mchid: '',
        carid: prop.item.id,
        orderid: '',
        rentid: '',
        area: '',
        name: '',
        mob: '',
        state: 0,
    },
    pager: {
        page: 1,
        size: 10,
        time: new Date().getTime(),
    },
})

const pager = ref({
    now: 1,
    row: 0,
    all: 0,
    fms: 0,
})
const items = ref([])

const doQuery = () => {
    param.value.pager.page = 1
    execLoad()
}

const execLoad = () => {
    Http.post('/ops/biz/order/list', param.value).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        if (resp.data.pager.now == 1) {
            param.value.pager.time = resp.data.pager.fms
        }
        pager.value = resp.data.pager
        items.value = resp.data.items
    })
}

const data = ref<any>({})

const viewActive = ref(false)

onBeforeMount(() => {
    execLoad()
})
</script>
